<?php

namespace App\Http\Controllers\admin;

use App\Models\AchievementCost;
use App\Models\AchievementCostDetail;
use App\Models\AchievementCostStandard;
use App\Models\RoleUser;
use App\Models\User;
use App\Models\Achievement;
use App\Http\Requests\AchievementCreateRequest;
use App\Http\Requests\AchievementUpdateRequest;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\Group;
use App\Http\Controllers\Admin\BaseController;
use  App\Models\Tips;
use phpDocumentor\Reflection\Types\Null_;
use Illuminate\Support\Facades\Response;

class CostController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $now= Carbon::now();
        $year=$request->input('year',$now->year);
        $month=$request->input('month',$now->month);
        $start= Carbon::create($year,$month,1,0,0,0)->toDateTimeString();
        $end= Carbon::create($year,$month+1,0,0,0,0)->toDateTimeString();
        if($month < 10){
            $month = '0'.$month;
        }

        $uid=$this->user->id;

        if( $this->user->getRole()==9){

            $sub=user::where('corpid',$this->corpid)->where('status','1')->where('is_sales','1')->with(['achievement'=>function($query)use($year,$month){
                $query->where('month_param',$year.$month);
            }])->get();
            foreach ($sub as $u){
                $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
                $u->month = AchievementCost::where('corpid',$this->corpid)->where('user_id',$u->id)->where('month_param',$year.$month)->first();
                if(!empty($u->month)){
                    $u->month->description =  str_replace('<br/>',PHP_EOL, $u->month->description);
                }
                $u->month_detail = AchievementCostDetail::where('corpid',$this->corpid)->where('user_id',$u->id)->where('month_param',$year.$month)->get();
            }
            



           //dd($sub);
            $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
            $groups = $groups->toArray();
            $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
            array_unshift($groups,$groups_add);
            $tongxunlu=[];
           // $sub = $sub->toArray();
            foreach ($groups as &$g){
                $g['member'] = $this->filterUser($g['id'],$sub);
                if($g['fid'] == 0){
                    $tongxunlu[] = $g;
                }
            }
            foreach ($tongxunlu as $k=>&$t){
                if($t['id'] !=0){
                    $t['child'] = $this->filterGroup($t['id'],$groups);
                    foreach ($t['child'] as &$cld){
                        $cld['child'] = $this->filterGroup($cld['id'],$groups);
                    }
                }
            }
        }else{
            $scope=unserialize(RoleUser::where('user_id',$uid)->where("role_id",11)->first()->scope);
            if (!$scope==false){
                $sub=user::wherein('id',$scope)->where('status','1')->where('is_sales','1')->with(['achievement'=>function($query)use($start,$end){
                    $query->whereBetween('created_at',[$start,$end]);
                }])->get();
            }else{
                $sub=user::where('corpid',$this->corpid)->where('status','1')->where('is_sales','1')->with(['achievement'=>function($query)use($start,$end){
                    $query->whereBetween('created_at',[$start,$end]);
                }])->get();
            }


     //       dd($sub);
            foreach ($sub as $u){
                $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
                $u->month = AchievementCost::where('corpid',$this->corpid)->where('user_id',$u->id)->where('month_param',$year.$month)->first();
                if(!empty($u->month)){
                    $u->month->description =  str_replace('<br/>',PHP_EOL, $u->month->description);
                }
                $u->month_detail = AchievementCostDetail::where('corpid',$this->corpid)->where('user_id',$u->id)->where('month_param',$year.$month)->get();
            }


            $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
            $groups = $groups->toArray();
            $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
            array_unshift($groups,$groups_add);
            $tongxunlu=[];
            // $sub = $sub->toArray();
            foreach ($groups as &$g){
                $g['member'] = $this->filterUser($g['id'],$sub);
                if($g['fid'] == 0){
                    $tongxunlu[] = $g;
                }
            }
            foreach ($tongxunlu as $k=>&$t){
                if($t['id'] !=0){
                    $t['child'] = $this->filterGroup($t['id'],$groups);
                    foreach ($t['child'] as &$cld){
                        $cld['child'] = $this->filterGroup($cld['id'],$groups);
                    }
                }
            }
        }


        $tips=Tips::where("corpid",$this->corpid)->get();
      //  dd($tips);
        if(is_mobile()){
            $view = 'admin.achievement.sale-achivement';
        }else{
            $view = 'pc_admin.achievement.xxx';
        }
        $rolearray = array('9'=>'总','10'=>'考','11'=>'业','12'=>'奖');
       // dd($tongxunlu);
        return view($view)->with('tongxunlu',$tongxunlu)->with('user',$this->user)
            ->with('year',$year)->with('month',$month)->with('start',$start)->with('roleArray',$rolearray)->with( 'tips', $tips);
    }

    private function filterUser($group_id,$users){
        $return = array();
        foreach ($users as $u){
            if($u['group_id'] == $group_id){
                $return[] = $u;
            }
        }
        return $return;
    }

    private function filterGroup($group_id,$groups){
        $return = array();
        foreach ($groups as $u){
            if($u['fid'] == $group_id){
                $return[] = $u;
            }
        }
        return $return;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //

    }


    public function postMonthStore(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        $data = $request->all();

        $data['corpid']=$this->corpid;
        $data['year_param']= date('Y',strtotime($data['time']));
        $data['month_param']= date('Ym',strtotime($data['time']));
        $title = $request->input('title','');
        $detail = $request->input('detail','');
        $user_id = $request->input('user_id','');

        $detail = str_replace(PHP_EOL, '<br/>', $detail);

        if(strlen($title) > 25){
            $result['status'] = 'fail';
            $result['msg'] = '标题10字以内';
            return Response::json($result);
        }



        $exist = AchievementCost::where('month_param',$data['month_param'])->where('user_id',$user_id)->where('corpid',$this->corpid)->first();
        if(empty($exist)){
            $exist = new AchievementCost();
            $exist->user_id = $user_id;
            $exist->corpid = $this->corpid;
            $exist->year_param = $data['year_param'];
            $exist->month_param = $data['month_param'];
            $exist->name = $title;
            $exist->description = $detail;
        }else{
            $exist->name = $title;
            $exist->description = $detail;
        }
        $exist->save();

        $result['msg'] = '标题描述保存成功';
        return Response::json($result);
    }


    public function postMonthDetailStore(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        $data = $request->all();

        $data['corpid']=$this->corpid;
        $data['year_param']= date('Y',strtotime($data['time']));
        $data['month_param']= date('Ym',strtotime($data['time']));
        $score = $request->input('cost','');
        $did = $request->input('did',0);
        $user_id = $request->input('user_id','');

        if(!is_positive_int($did) && $did != 0){
            $result['status'] = 'fail';
            $result['msg'] = 'id错误';
            return Response::json($result);
        }

        if(!is_numeric($score) || $score < 0){
            $result['status'] = 'fail';
            $result['msg'] = '费用必须是大于0数字';
            return Response::json($result);
        }
        

        if($did > 0){
            $exist = AchievementCostDetail::find($did);
            if(empty($exist)){
                $result['status'] = 'fail';
                $result['msg'] = 'id未找到';
                return Response::json($result);
            }
            $exist->score = $score;
            $exist->save();
        }else{
            $exist = new AchievementCostDetail();
            $exist->user_id = $user_id;
            $exist->corpid = $this->corpid;
            $exist->score = $score;
            $exist->year_param = $data['year_param'];
            $exist->month_param = $data['month_param'];
            $exist->save();
        }

        $result['msg'] = '保存成功';
        $result['data'] = $exist->id;
        return Response::json($result);
    }


    public function postMonthDetailDelete(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        $data = $request->all();

        $data['corpid']=$this->corpid;
        $did = $request->input('id',0);
        if(!is_positive_int($did)){
            $result['status'] = 'fail';
            $result['msg'] = 'id不存在！';
            return Response::json($result);
        }

        $exist = AchievementCostDetail::where('corpid',$this->corpid)->find($did);
        if(empty($exist)){
            $result['status'] = 'fail';
            $result['msg'] = '记录不存在！';
            return Response::json($result);
        }
        $exist->delete();


        $result['msg'] = '删除成功';
        return Response::json($result);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AchievementCreateRequest $request)
    {
        //
        $data=$request->FillData();
        $data['corpid']=$this->corpid;
        $data['year_param']= date('Y',strtotime($data['created_at']));
        $data['month_param']= date('Ym',strtotime($data['created_at']));

        if ( $data["tip_id"]==0){
            $data["tip_id"]=Null;
        }
        $data=Achievement::create($data);
        return  $this->formatJson('success','创建成功',$data,'/admin/init/'.$data->id.'/edit');
    }

    /**  ay the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(AchievementUpdateRequest $request, $id)
    {
        //
        $data=$request->FillData();
        $Achievement=Achievement::find($id);
        $Achievement->update($data);

        return  $this->formatJson('success','创建成功',$Achievement);
    }


    //筛选用户

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(Achievement::destroy((int)$id)){
            return  $this->formatJson('success','删除成功');
        }else{
            return  $this->formatJson('error','异常');
        }

    }

    //筛选组

    public function check(Request $request)
    {
        $tongxunlu = array();
        $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
        $groups = $groups->toArray();
        $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
        array_unshift($groups,$groups_add);

        $now= Carbon::now();
        $year=$request->input('year',$now->year);
        $month=$request->input('month',$now->month);

        if( $month==0){  //全年
            $start= Carbon::create($year,1,1,0,0,0)->toDateTimeString();
            $end= Carbon::create($year,12+1,0,23,59,59)->toDateTimeString();
            $month="全年";
        }else{
            $start= Carbon::create($year,$month,1,0,0,0)->toDateTimeString();
            $end= Carbon::create($year,$month+1,0,0,0,0)->toDateTimeString();
        }

        $users = User::where('corpid',$this->corpid)->where('status','1')->with(['achievement'=>function($query)use($start,$end){
            $query->whereBetween('created_at',[$start,$end]);
        }])->get();
        foreach ($users as $u){
            $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
        }
        foreach ($groups as &$g){
            $g['member'] = $this->filterUser($g['id'],$users);
            if($g['fid'] == 0){
                $tongxunlu[] = $g;
            }
        }
        foreach ($tongxunlu as $k=>&$t){
            if($t['id'] !=0){
                $t['child'] = $this->filterGroup($t['id'],$groups);
                foreach ($t['child'] as &$cld){
                    $cld['child'] = $this->filterGroup($cld['id'],$groups);
                }
            }
        }
        if(is_mobile()){
            $view = 'admin.achievement.check';
        }else{
            $view = 'pc_admin.achievement.check';
        }

        return view($view)->with('tongxunlu',$tongxunlu)->with('roleArray',$this->roleArray)->with('year',$year)->with('month',$month)->with('user',$this->user);
    }


    public function getStandard(Request $request)
    {
        $now= Carbon::now();
        $year=$request->input('year',$now->year);
        $month=$request->input('month',$now->month);
        $start= Carbon::create($year,$month,1,0,0,0)->toDateTimeString();
        $end= Carbon::create($year,$month+1,0,0,0,0)->toDateTimeString();


        $uid=$this->user->id;

        if( $this->user->getRole()==9){
            $standard = AchievementCostStandard::where('month_param',$year.$month)->where('corpid',$this->corpid)->first();
        }else{
            $standard = null;
            abort('403','仅支持系统管理员查看');
        }


        $tips=Tips::where("corpid",$this->corpid)->get();
        //  dd($tips);
        if(is_mobile()){
            $view = 'admin.achievement.standard-scale';
        }else{
            $view = 'pc_admin.achievement.xxx';
        }
        $rolearray = array('9'=>'总','10'=>'考','11'=>'业','12'=>'奖');
        // dd($tongxunlu);
        return view($view)
            ->with('year',$year)->with('month',$month)->with('standard',$standard)->with('user',$this->user)->with('start',$start);
    }


    public function postStandardStore(Request $request)
    {
        $result = array(
            'status'        => 'fail',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        $data = $request->all();

        $data['corpid']=$this->corpid;
        $data['year_param']= date('Y',strtotime($data['time']));
        $data['month_param']= date('Ym',strtotime($data['time']));
        $percent = $request->input('cost','');


        if(!is_numeric($percent) || $percent > 100 || $percent < 0){
            $result['msg'] = '错误，比例应该为0-100';
            return Response::json($result);
        }


        $exist = AchievementCostStandard::where('month_param',$data['month_param'])->where('corpid',$this->corpid)->first();
        if(empty($exist)){
            $exist = new AchievementCostStandard();
            $exist->corpid = $this->corpid;
            $exist->year_param = $data['year_param'];
            $exist->month_param = $data['month_param'];
            $exist->percent = $percent;
        }else{
            $exist->percent = $percent;
        }
        $exist->save();

        $result['status'] = 'success';
        $result['msg'] = '保存成功';
        return Response::json($result);
    }


    public function postStandardDelete(Request $request)
    {
        $result = array(
            'status'        => 'fail',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        $data = $request->all();

        $data['corpid']=$this->corpid;
        $data['year_param']= date('Y',strtotime($data['time']));
        $data['month_param']= date('Ym',strtotime($data['time']));
        


        $exist = AchievementCostStandard::where('month_param',$data['month_param'])->where('corpid',$this->corpid)->first();
        if(empty($exist)){
            $result['msg'] = '记录不存在或已删除';
            return Response::json($result);
        }else{
            $exist->delete();
        }

        $result['status'] = 'success';
        $result['msg'] = '删除成功';
        return Response::json($result);
    }
}
